﻿using System.Collections;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace Brilliant_see.MapSources.Enumerators
{
    public class BaoziPicEnumerator : IEnumerator<string>
    {
        private readonly HttpClient _client;
        private string _url;
        private int _index = 0;
        private int _count = 0;
        private string _format = string.Empty;
        private Task? _task;

        public string Current => string.Format(_format, _index);

        object IEnumerator.Current => Current;

        internal BaoziPicEnumerator(string url, HttpClient client)
        {
            _url = url;
            _client = client;
            _task = InitAsync();
        }

        public bool MoveNext()
        {
            _index++;

            if (_count < _index)
            {
                if (_task is not null && !_task.IsCompleted)
                    _task.Wait();

                if (_count < _index) return false;
            }

            return true;
        }

        public void Reset() => _index = 0;

        public void Dispose()
        {
            _url = _format = string.Empty;
            _task = null;
        }

        private async Task InitAsync()
        {
            var msg = (await _client.GetAsync(_url));
            if (msg.RequestMessage is null || msg.RequestMessage.RequestUri is null)
                throw new Exception("包子漫画接口异常");

            _url = msg.RequestMessage.RequestUri.AbsoluteUri;
            var html = (await msg.Content.ReadAsStringAsync()).Replace("\n", string.Empty);
            var match = Regex.Match(html, "<noscript.+?><img src=\"(.+?)\".+?<em.+?>.+?/(\\d+?)\\D");
            var picUrl = match.Groups[1].Value;
            if (string.IsNullOrEmpty(picUrl)) return;

            _format = picUrl.Replace("/1.jpg", "/{0}.jpg");
            _count = int.Parse(match.Groups[2].Value);

            if (html.Contains("点击进入下一页"))
                GetTotal(2);
        }

        private async void GetTotal(int index)
        {
            var url = _url.Replace(".html", $"_{index}.html");
            var html = await _client.GetStringAsync(url);
            if (html.Contains("点击进入下一页"))
            {
                GetTotal(++index);
                return;
            }

            html = html.Replace("\n", string.Empty);
            var macthes = Regex.Matches(html, "<em data-v-.+?>.*?(\\d+?)/");
            var count = macthes.Count;
            if (count < 1) throw new Exception("获取包子漫画总页数异常");
            _count = int.Parse(macthes[count - 1].Groups[1].Value);
        }
    }
}